function getElementById(id) {
    return document.getElementById(id);
}
var Ajax = {
    ajax: function (param) {
        var url = param['url'];
        if (isEmpty(url)) {
            param.error.call(this, "url不能为空");
            return false;
        }
        var dataType = param["dataType"];
        var type = param["type"];
        var data = param["data"];
        var methodType = "POST";
        var requestData = "";
        if (data != null && data != undefined) {
            // 参数转换
            var objs = Object.keys(data);
            for (var i = 0,len = objs.length, key = ""; i < len; i++) {
                key = objs[i];
                if (i >= 1) {
                    requestData += "&";
                }
                requestData += key + "=" + data[key];
            }
        }
        if (isEmpty(type) || type.toLowerCase() == "get") {
            methodType = "GET";
            if (url.indexOf("?") != -1 && requestData != "") {
                // 如果url有参数重新拼接
                url += "&" + requestData;
            } else {
                url += "?"+ requestData;
            }
        }
        this.send(url, methodType, data, dataType, param.success, param.error)
    },
    /**
     * 发送ajax请求
     *
     * @param url 请求链接
     * @param methodType 请求方法 POST、GET
     * @param data 请求数据
     * @param dataType 返回数据类型
     * @param success 成功回调
     * @param error 失败回调
     */
    send: function (url, methodType, data, dataType, success, error) {
        // XMLHttpRequest对象用于在后台与服务器交换数据
        var xhr = new XMLHttpRequest();
        xhr.open(methodType, url , true);
        if (methodType == "POST") {
            // 添加http头，发送信息至服务器时内容编码类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        //每当readyState改变时就会触发onreadystatechange函数
        //0: 请求未初始化
        //1: 服务器连接已建立
        //2: 请求已接收
        //3: 请求处理中
        //4: 请求已完成，且响应已就绪
        xhr.onreadystatechange = function() {
            if (xhr.readyState != 4) {
                return;
            }
            if (xhr.status == 200 || xhr.status == 304) {
                try {
                    if (dataType != null && dataType.toLowerCase() == "json") {
                        success.call(this, JSON.parse(xhr.responseText));
                    } else {
                        success.call(this, xhr.responseText);
                    }
                } catch (e) {
                    error.call(this, e);
                }
            } else{
                error.call(this, xhr);
            }
        };
        //发送数据
        xhr.send(data);
    }
}

function isEmpty(str) {
    if (str == null || str == undefined || str == "") {
        return true;
    }
    return false;
}

var isLogin = false;
var isVip = false;

Ajax.ajax({
    type: "GET",
    url: "/user/login-status",
    dataType: "JSON",
    //请求成功
    success: function (result) {
        if (result.code == 1) {
            var name = result.data.username;
            if (result.data.nickname != null) {
                name = result.data.nickname;
            }
            var usernameObj = document.getElementById("login_info");
            var loginMenu = document.getElementById("login_menu");
            loginMenu.style.visibility = "visible";
            //getElementById("login_btn").style.display = "none";
            if( strLen(name) > 8) {
                name = name.slice(0,4) + ".";
            } else {
                name = "&nbsp;" + name + "&nbsp;";
            }
            usernameObj.innerHTML = "&nbsp;" + name + "&nbsp;";
            usernameObj.style.color = "#FF455B";

            // getElementById("avatar").src = "https://tv.speechb.com/" + (result.data.avatar_url);
            // getElementById("logined").style.display = "block";
            // getElementById("menu").style.display = "block";
            getElementById("logout").onclick  = function () {
                logout();
            };
            isLogin = true;
        } else {
            isLogin = false;
        }
    },
    //请求失败，包含具体的错误信息
    error: function (e) {
    }
});

function logout() {
    Ajax.ajax({
        type: "GET",
        url: "/user/logout",
        dataType: "JSON",
        success: function (result) {
            if (result.code == 1) {
                var usernameObj = document.getElementById("login_info");
                var loginMenu = document.getElementById("login_menu");
                loginMenu.style.visibility = "hidden";
                usernameObj.innerHTML = "&nbsp;" + '登录' + "&nbsp;";
                usernameObj.style.color = "#FFFFFF";
            }
        },
        //请求失败，包含具体的错误信息
        error: function (e) {

        }
    });
}
function refresh() {
    if(sessionStorage.getItem('refresh') === 'true') {
        // 刷新当前页面
        sessionStorage.removeItem('refresh');
        location.reload();
    }
}
refresh();
if(getElementById("buy_ca")) {
    getElementById("buy_ca").onclick = function () {
        window.location.href = "/buy-vip";
    }
}

function strLen(str) {
    //先把中文替换成两个字节的英文，在计算长度
    return str.replace(/[\u0391-\uFFE5]/g,"aa").length;
};

function toast(msg,duration){
    duration=isNaN(duration)?3000:duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText="max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 10%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
    document.body.appendChild(m);
    setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
    }, duration);
}